package com.example;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class SHA256WithSalt {

    // 生成随机盐值
    private static byte[] generateSalt(int length) {
        String salt = "U9i%=N+m]#i9yvUV:bA/3n4X9JdPXf=n";
        return salt.getBytes();
    }

    // 将字节数组转换为十六进制字符串
    private static String toHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }

    // 使用 SHA-256 算法对密码和盐值进行加密
    public static String hashPassword(String password, byte[] salt) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(salt);
        byte[] hashedBytes = messageDigest.digest(password.getBytes());
        return toHex(hashedBytes);
    }

    public static void main(String[] args) {
        try {
            String password = "secret";
            byte[] salt = generateSalt(16); // 生成 16 字节的盐值
            String hashedPassword = hashPassword(password, salt);

            // 将盐值和哈希值一起存储
            String saltBase64 = Base64.getEncoder().encodeToString(salt);
            System.out.println("Salt: " + saltBase64);
            System.out.println("Hashed Password: " + hashedPassword);

            // 验证密码
            String inputPassword = "SecretPassword";
            byte[] inputSalt = Base64.getDecoder().decode(saltBase64);
            String inputHashedPassword = hashPassword(inputPassword, inputSalt);
            if (inputHashedPassword.equals(hashedPassword)) {
                System.out.println("Password is correct.");
            } else {
                System.out.println("Password is incorrect.");
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}
